home *** CD-ROM | disk | FTP | other *** search
- Path: svnews.ubinet.ubs.com!ubszh!ian.johnston@ubs.com
- From: ian.johnston@ubs.com (Ian Johnston (by ubsswop))
- Newsgroups: comp.lang.c++
- Subject: Re: Friend vs. Member function for operator overload
- Date: 12 Apr 1996 07:57:19 GMT
- Organization: UBS
- Distribution: world
- Message-ID: <4kl2cv$bpm@ubszh.fh.zh.ubs.com>
- References: <4kj55n$mv2@homenet.hom.net>
- NNTP-Posting-Host: nol2179.fh.zh.ubs.com
-
- In article <4kj55n$mv2@homenet.hom.net>, dengel@hom.net (Daniel P. Engel III) writes:
- |> Can anyone tell me the relative advantages and disadvantages of using
- |> a friend function vs. a member function to overload an operator, such
- |> as addition? For example, suppose you have a Complex class (I'm not
- |> interested in building a complex class--I'm just using this for an
- |> example.):
-
- [...]
-
- |> Can anyone tell me if one of these the "preferred" way of doing it?
- |> And, what are the advantages and disadvantages of each?
-
- When the operator + is a member of the class, the left hand argument
- must be a class member:
-
- x = aComplex + aDouble; // Works
- x = aDouble + aComplex; // Doesnt work
- // (or at least, doesnt
- // use Complex::operator +())
-
- When the operator + is a friend, you can define a version where the
- lhs is a class object, and a version where the lhs is a builtin. Then:
-
- x = aComplex + aDouble; // operator + (Complex const &, double)
- x = aDouble + aComplex; // operator + (double, Complex const &)
-
-
- Personally, I prefer the friend functions for this reason.
-
- Ian
-